package com.panda.aspect;


import com.alibaba.fastjson.JSON;
import com.panda.annotation.SystemLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: panda
 * @Date: 2022-05-18 15:03
 * @Description: 日志切面编程，copy
 */

@Component
@Aspect
@Slf4j
public class LogAspect {



    private void handleBefore(ProceedingJoinPoint joinPoint) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        SystemLog systemLog = getSystemLog(joinPoint);

        log.info("====== START ======");
        log.info("URL            : {}", request.getRequestURL());
        log.info("BusinessName   : {}", systemLog.businessName());
        log.info("Http Method    : {}", request.getMethod());
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        log.info("IP             : {}", request.getRemoteHost());
        log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));


    }


    @Around("@annotation(com.panda.annotation.SystemLog)")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object ret;
        try {
            handleBefore(joinPoint);
            ret = joinPoint.proceed();
            handleAfter(ret);

        } finally {
            log.info("======= END =======" + System.lineSeparator());
        }
        return ret;
    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        return methodSignature.getMethod().getAnnotation(SystemLog.class);
    }

    private void handleAfter(Object ret) {
        log.info("Response       : {}", JSON.toJSONString(ret));
    }

}
